package com.qrback.controller;

import com.qrback.entity.User;
import com.qrback.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/auth")
public class UserAuthController {
    
    @Autowired
    private UserService userService;
    
    // 用户注册
    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody User user) {
        try {
            // 检查手机号是否已存在
            if (userService.existsByPhone(user.getPhone())) {
                return ResponseEntity.badRequest().body("手机号已被注册");
            }
            
            // 设置默认角色为普通用户
            if (user.getRole() == null) {
                user.setRole(User.Role.user);
            }
            
            User createdUser = userService.createUser(user);
            return ResponseEntity.status(HttpStatus.CREATED).body(createdUser);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
        }
    }
    
    // 密码登录
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody LoginRequest loginRequest) {
        try {
            String token = userService.login(loginRequest.getPhone(), loginRequest.getPassword());
            
            // 获取用户信息
            User user = userService.getUserByPhone(loginRequest.getPhone())
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            
            // 构建用户信息对象，不包含密码
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("id", user.getId());
            userInfo.put("phone", user.getPhone());
            userInfo.put("role", user.getRole());
            userInfo.put("createdAt", user.getCreatedAt());
            userInfo.put("updatedAt", user.getUpdatedAt());
            
            // 构建响应对象
            Map<String, Object> response = new HashMap<>();
            response.put("token", token);
            response.put("user", userInfo);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(e.getMessage());
        }
    }
    
    // 发送验证码
    @PostMapping("/send-code")
    public ResponseEntity<?> sendVerificationCode(@RequestBody PhoneRequest phoneRequest) {
        try {
            userService.sendVerificationCode(phoneRequest.getPhone());
            return ResponseEntity.ok("验证码已发送");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
        }
    }
    
    // 验证码登录
    @PostMapping("/login/code")
    public ResponseEntity<?> loginWithCode(@RequestBody VerificationCodeRequest codeRequest) {
        try {
            String token = userService.loginWithVerificationCode(codeRequest.getPhone(), codeRequest.getCode());
            
            // 获取用户信息
            User user = userService.getUserByPhone(codeRequest.getPhone())
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            
            // 构建用户信息对象，不包含密码
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("id", user.getId());
            userInfo.put("phone", user.getPhone());
            userInfo.put("role", user.getRole());
            userInfo.put("createdAt", user.getCreatedAt());
            userInfo.put("updatedAt", user.getUpdatedAt());
            
            // 构建响应对象
            Map<String, Object> response = new HashMap<>();
            response.put("token", token);
            response.put("user", userInfo);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(e.getMessage());
        }
    }
    
    // 退出登录
    @PostMapping("/logout")
    public ResponseEntity<?> logout() {
        try {
            // 简化实现，实际项目中可能需要在后端做一些清理工作，如使token失效等
            // 前端通常会清除localStorage中的token
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
        }
    }
    
    // 刷新Token
    @PostMapping("/refresh-token")
    public ResponseEntity<?> refreshToken(@RequestBody RefreshTokenRequest refreshTokenRequest) {
        try {
            // 简化实现，实际项目中需要验证旧token并生成新token
            // 这里直接返回一个模拟的新token
            String newToken = "refreshed_jwt_token";
            
            Map<String, Object> response = new HashMap<>();
            response.put("token", newToken);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(e.getMessage());
        }
    }
    
    // 请求参数类
    static class LoginRequest {
        private String phone;
        private String password;
        
        // getter and setter
        public String getPhone() { return phone; }
        public void setPhone(String phone) { this.phone = phone; }
        public String getPassword() { return password; }
        public void setPassword(String password) { this.password = password; }
    }
    
    static class PhoneRequest {
        private String phone;
        
        // getter and setter
        public String getPhone() { return phone; }
        public void setPhone(String phone) { this.phone = phone; }
    }
    
    static class VerificationCodeRequest {
        private String phone;
        private String code;
        
        // getter and setter
        public String getPhone() { return phone; }
        public void setPhone(String phone) { this.phone = phone; }
        public String getCode() { return code; }
        public void setCode(String code) { this.code = code; }
    }
    
    static class RefreshTokenRequest {
        private String token;
        
        // getter and setter
        public String getToken() { return token; }
        public void setToken(String token) { this.token = token; }
    }
}